package com.woniuxy.juc.reentrant;

import com.woniuxy.untis.Sleep;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 可重入锁的多条件使用
 * <P> Date: 2022/4/8:8:48
 * <P> Description:
 */
@Slf4j(topic = "c.ReentrantLockTest5")
public class ReentrantLockTest5 {
    private static ReentrantLock ROOM = new ReentrantLock();
    //TODO 等待烟的休息室
    static Condition waitCigarette = ROOM.newCondition();
    //TODO 等待外卖的休息室
    static Condition waitTakeout = ROOM.newCondition();
    static boolean hasCigarette = false;
    static boolean hasTakeout = false;

    public static void main(String[] args) {
        new Thread(() -> {
            ROOM.lock();
            try {
                log.debug("有烟没？[{}]", hasCigarette);
                while (!hasCigarette) {
                    log.debug("没烟，先歇会！");
                    try {
                        waitCigarette.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("可以开始干活了");

            } finally {
                ROOM.unlock();
            }

        }, "小南").start();

        new Thread(() -> {
            ROOM.lock();
            try {
                log.debug("外卖到了？[{}]", hasTakeout);
                while (!hasTakeout) {
                    log.debug("外卖没到，先歇会！");
                    try {
                        waitTakeout.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("可以开始干活了");

            } finally {
                ROOM.unlock();
            }

        }, "小女").start();


        Sleep.sleep(1000);
        new Thread(() -> {

            ROOM.lock();
            try {
                log.debug("外卖到了！");
                hasTakeout = true;
                waitTakeout.signal();
            } finally {
                ROOM.unlock();
            }
        }, "外卖的").start();

        new Thread(() -> {
            ROOM.lock();
            try {
                log.debug("送烟到了！");
                hasCigarette = true;
                waitCigarette.signal();
            } finally {
                ROOM.unlock();
            }

        }, "送烟的").start();


    }
}
